// 日志处理类

package zyplog

import (
	"errors"
	"log"
	"log/syslog"
	"os"
)

type LogType int

// 日志类别
const (
	LOG_STDOUT LogType = iota
	LOG_FILE
	LOG_SYSLOG
)

const (
	PREFIX_INFO    string = " [INFO] "
	PREFIX_WARNING string = " [WARNING] "
	PREFIX_ERROR   string = " [ERROR] "
)

type ZypLoger struct {
	logInfo    *log.Logger
	logWarning *log.Logger
	logError   *log.Logger

	logType LogType
	logFile *os.File
}

func NewZypLoger(logType LogType, fileName string) (*ZypLoger, error) {
	zl := ZypLoger{logType: logType}
	var err error
	logFlag := log.Ldate | log.Ltime | log.Lmsgprefix
	processName := os.Args[0]

	switch logType {
	case LOG_STDOUT:
		zl.logInfo = log.New(os.Stdout, processName+PREFIX_INFO, logFlag)
		zl.logWarning = log.New(os.Stdout, processName+PREFIX_WARNING, logFlag)
		zl.logError = log.New(os.Stdout, processName+PREFIX_ERROR, logFlag)
	case LOG_FILE:
		if fileName == "" {
			return nil, errors.New("日志文件名不能为空")
		}
		zl.logFile, err = os.OpenFile(fileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
		if err != nil {
			return nil, err
		}

		zl.logInfo = log.New(zl.logFile, processName+PREFIX_INFO, logFlag)
		zl.logWarning = log.New(zl.logFile, processName+PREFIX_WARNING, logFlag)
		zl.logError = log.New(zl.logFile, processName+PREFIX_ERROR, logFlag)
	case LOG_SYSLOG:
		zl.logInfo, err = syslog.NewLogger(syslog.LOG_INFO, logFlag)
		if err == nil {
			zl.logWarning, err = syslog.NewLogger(syslog.LOG_WARNING, logFlag)
			if err == nil {
				zl.logError, err = syslog.NewLogger(syslog.LOG_ERR, logFlag)
			}
		}
		if err != nil {
			return nil, err
		}
	}

	return &zl, err
}

func (p *ZypLoger) Close() {
	if p.logType == LOG_FILE && p.logFile != nil {
		p.logFile.Close()
	}
}

func (p *ZypLoger) Info(args ...interface{}) {
	p.logInfo.Println(args...)
}

func (p *ZypLoger) Warning(args ...interface{}) {
	p.logWarning.Println(args...)
}

func (p *ZypLoger) Error(args ...interface{}) {
	p.logError.Println(args...)
}
